<template>
    <div>
        <!-- 发布评论 -->
        <el-form-item label="评论">
            <el-input maxlength="300" :show-word-limit="true" type="textarea" :autosize="true" placeholder="写下你的见解"
                style="width: 52vw;resize:none" v-model.trim="comment"></el-input><el-button type="primary"
                @click="sendComment">发布</el-button>
        </el-form-item>
        <!-- 评论区 -->
        <div class="building">
            <!-- 遍历各个楼主 -->
            <div class="landLord" v-for="(c, index) in commentList">
                <div class="userHead">
                    <el-image class="commentImg" :url="c.author.avatarUrl" style=""></el-image>
                    <span class="commentNickName">{{ c.author.nickname }}sfsdfsdf</span>
                    <span class="commentTime" style="color: #999;">{{ c.createTime }}</span>
                </div>
                <div class="landLordComment" style="color: black;">{{ c.content }}</div>

                <!-- 点赞爱心图标 -->
                <div class="smallIcon">
                    <iconify-icon icon="material-symbols:favorite-rounded" style="color: red"
                        v-show="isCommentLikeNum[c.id] == '1'" @click="checkCommentLike(c.id, index)" />
                    <iconify-icon icon="material-symbols:favorite-outline" @click="checkCommentLike(c.id, index)"
                        v-show="!isCommentLikeNum[c.id] || isCommentLikeNum[c.id] != '1'" />
                    <span class="titletext">{{ c.likeCount }}</span>
                </div>
                <!-- 回复楼主 -->
                <el-link @click="clickReply(index)">回复</el-link>
                <el-form-item label="评论" v-show="reply[index]">
                    <el-input maxlength="300" :show-word-limit="true" type="textarea" :autosize="true"
                        placeholder="写下你的见解" style="width: 40vw;resize:none"
                        v-model.trim="replyCommentContent"></el-input><el-button type="primary"
                        @click="sendReplyComment(c.id, index)">发布</el-button>
                </el-form-item>
                <!-- 遍历各个回复楼 -->
                <div class="member" v-for="(r, reindex) in replyList[c.id]">
                    <div class="replyHead">
                        <el-image class="replyImg" :url="r.author.avatarUrl" ></el-image>
                        <span class="replyNickName" style="color: black;">{{ r.author.nickname }}<span
                                v-if="(r.repliedUserNickname == undefined) ? false : true">&nbsp;回复&nbsp;</span>{{ r.repliedUserNickname
                            }}</span>
                        <span class="replyTime" style="color: #999;">{{ r.createTime }}</span>
                    </div>
                    <div class="landLordComment" style="color: black;font-size: 14px;">{{ r.content }}</div>
                    <!-- 回复楼主 -->
                    <div class="smallIcon">
                        <iconify-icon icon="material-symbols:favorite-rounded" style="color: red"
                            v-show="isReplyLikeNum[r.id] == '1'" @click="checkReplyLike(c.id, r.id, reindex)" />
                        <iconify-icon icon="material-symbols:favorite-outline"
                            @click="checkReplyLike(c.id, r.id, reindex)"
                            v-show="!isReplyLikeNum[r.id] || isReplyLikeNum[r.id] != '1'" />
                        <span class="titletext">{{ r.likeCount }}</span>
                    </div>
                    <!-- 回复评论回复的人 -->
                    <el-link @click="clickReReply(reindex)">回复</el-link>
                    <el-form-item label="评论" v-show="reReply[reindex]">
                        <el-input maxlength="300" :show-word-limit="true" type="textarea" :autosize="true"
                            placeholder="写下你的见解" style="width: 40vw;resize:none"
                            v-model.trim="reReplyCommentContent"></el-input><el-button type="primary"
                            @click="sendReReplyComment(c.id, r.id, reindex, r.author.nickname, index)">发布</el-button>
                    </el-form-item>
                </div>
                <!-- 回复评论 -->
                <el-link @click="showReply(c.id, index)" v-show="c.replyCount > (addReply[c.id] || 0)">展开<num
                        v-show="!addReply[c.id]">{{ c.replyCount + '条回复' }}</num>
                    <num v-show="addReply[c.id]">更多</num>
                </el-link>
                <el-link @click="closeReply(c.id)" v-show="showClose[c.id]">收起</el-link>
            </div>
        </div>
        <el-link @click="getMoreComment" v-show="(commentList.length == addComment) ? true : false">更多评论</el-link>
    </div>
</template>

<script setup lang="ts">
import { ref, toRefs, reactive } from 'vue';
import { useRoute } from 'vue-router';
import axios from 'axios';
import { add } from 'lodash';
// 接收父组件传来参数值
const props = defineProps(['recipeId'])
let recipeId = ref(props.recipeId)
// 评论发布的信息
let comment = ref()

// 评论信息接口
interface author {
    id: number
    nickname: string
    avatarUrl: string
    isAdmin: string
}
interface comment {
    author: author
    content: string
    createTime: string
    id: number
    likeCount: number
    replyCount: number
}
let commentList: comment[] = reactive([])
let getCommentListAxios: any
// 通过接口拿到评论列表
getComment(true)//传值默认为true
async function getComment(getLike: boolean) {
    getCommentListAxios = await axios({
        url: '/api/comment/getCommentList',
        method: 'post',
        data: {
            limit: 10,
            offset: 0,
            recipeId: recipeId.value
        }
    })
    Object.assign(commentList, getCommentListAxios.data.data)
    // getLike为true时
    if (getLike) {
        // 遍历每一个楼主评论
        await Promise.all(commentList.map((item, index) =>
            // 获取每个楼主评论的点赞状态，传入评论id
            getCommentLikeDataFrom(item.id, index, item.content)
        ))
    }
}

// 发送评论
function sendComment() {
    // 判断评论是否为空，为空则不发送
    if (!comment.value) {
        console.log(false);
    } else {
        axios({
            url: '/api/comment/addComment',
            method: 'post',
            data: {
                content: comment.value,
                recipeId: recipeId.value
            },
            headers: { 'content-type': 'application/json' }
        }).then(res => {
            comment.value = ''//发送成功则将评论置为空
            // 获取评论成功后的评论列表
            getComment(true)
        })
    }
}


let addComment = ref(10)//默认更多评论添加数
// 获取更多评论
function getMoreComment() {
    axios({
        url: '/api/comment/getCommentList',
        method: 'post',
        data: {
            limit: 10 + addComment.value,
            offset: 0,
            recipeId: recipeId.value
        }
    }).then(res => {
        Object.assign(commentList, res.data.data)
    })
    addComment.value = addComment.value + 10
}


let reply = ref([false])//判断点击回复后是否出现输入框，默认为false,为数组形式
// 点击展示回复评论的输入框
function clickReply(index: number) {
    // 先保存被点击评论的回复标签的原始值,便于判断是否是自己点自己
    let show = reply.value[index]
    // 再将回复和回复回复置为false
    reply.value = [false]
    reReply.value = [false]
    // 如果是自己点自己则将自己原本的true转为false,(也就是再次点击输入框消失)，如果不是自己点自己，那就将被点击的评论置为true,
    reply.value[index] = !show
    // reply.value[index] = !reply.value[index]
}


// 获取回复评论的信息
let replyCommentContent = ref()
// 给接口传参的回复对象
interface replyMe {
    commentId: number
    content: string
    recipeId: number
}
let replyMessage: replyMe = {
    commentId: -1,
    content: '',
    recipeId: -1,
}
// 发送回复评论
function sendReplyComment(id: number, index: number) {
    commentList[index].replyCount = commentList[index].replyCount + 1

    reply.value[index] = false//发送完输入框消失
    if (!replyCommentContent.value) {//如果回复输入框为空则打印false
        console.log(false);
    } else {
        replyMessage = {
            commentId: id,
            content: replyCommentContent.value,
            recipeId: recipeId.value
        }
        axios({
            url: '/api/reply/addReply',
            method: 'post',
            data: JSON.stringify(replyMessage),
            headers: { 'Content-Type': 'application/json' }
        }).then(res => {
            replyCommentContent.value = ''//将输入框置为空
            showReply(id, 0)//展示回复评论
        })
    }
}


interface reply {//回复对象
    code: number
    author: author
    content: string
    repliedUserNickname: string
    id: number
    createTime: string
    likeCount: number
}
// 现在来看像是一个二维数组，一维只存数字，二维存一维数字所指向的数组，整个则是一个对象
let replyList: Record<number, reply[]> = reactive({})//以id为唯一键值，独立判断回复列表展示
let getReplyAxios: any
let addReply = ref<Record<number, number>>({})//以id为唯一键值，独立判断回复展开
let showClose = ref<Record<number, boolean>>({})//以id为唯一键值，独立判断评论收起

// 展示回复
async function showReply(cid: number, index: number) {
    const ReplyObj = {
        commentId: cid,//评论id
        limit: 3 + (addReply.value[cid] || 0),
        offset: 0,
    }
    showClose.value[cid] = true//展开回复，便将收起显示
    getReplyAxios = await axios({
        url: '/api/reply/getReplyList',
        method: 'post',
        data: JSON.stringify(ReplyObj),
        headers: { 'Content-Type': 'application/json' }
    })
    addReply.value[cid] = (addReply.value[cid] || 0) + 3//通过id键值，独立控制每个回复展开个数
    replyList[cid] = getReplyAxios.data.data//拿到展开的回复列表
    // 拿到回复列表执行一下操作
    if (replyList[cid]) {
        // 遍历拿到的每个回复的点赞状态
        await Promise.all(replyList[cid].map(async (replyItem) => {
            try {
                const response = await axios({
                    url: '/api/like/getLikeReplyRecord',
                    params: { commentId: replyItem.id }
                })
                if (response.data.data) {
                    getReplyLikeData[replyItem.id] = response.data.data
                    isReplyLikeNum.value[replyItem.id] = response.data.data.isLiked
                } else {
                    isReplyLikeNum.value[replyItem.id] = ''
                }
            } catch (error) {
                console.error('获取回复点赞状态失败:', error)
                isReplyLikeNum.value[replyItem.id] = ''
            }
        }))
    }
}

// 展示回复回复输入框
let reReply = ref([false])
function clickReReply(index: number) {
    // 同理回复
    let show = reReply.value[index]
    reReply.value = [false]
    reply.value = [false]
    reReply.value[index] = !show
}


let reReplyCommentContent = ref()//回复回复输入框
interface reReplyMe {
    commentId: number
    content: string
    recipeId: number
    replyId: number
    repliedUserNickname: string
}
let reReplyMessage: reReplyMe = {
    commentId: -1,
    content: '',
    recipeId: -1,
    replyId: -1,
    repliedUserNickname: ''
}
// 回复回复输入框信息
function sendReReplyComment(cid: number, rid: number, reindex: number, rNickName: string, index: number) {
    commentList[index].replyCount = commentList[index].replyCount + 1
    reReply.value[reindex] = false//发送完，输入框消失
    if (!reReplyCommentContent.value) {
        console.log(false);
    } else {
        reReplyMessage = {
            commentId: cid,
            content: reReplyCommentContent.value,
            recipeId: recipeId.value,
            replyId: rid,
            repliedUserNickname: rNickName
        }
        axios({
            url: '/api/reply/addReply',
            method: 'post',
            data: JSON.stringify(reReplyMessage),
            headers: { 'Content-Type': 'application/json' }
        }).then(res => {
            reReplyCommentContent.value = ''//输入框置为空
            showReply(cid, 0)//展示输入的回复
        })
    }
}

// 收起按键
function closeReply(cid: number) {
    showClose.value[cid] = false//收起消失
    addReply.value[cid] = 0//更多回复出现
    replyList[cid].length = 0//对应id的回复列表置为空
}

// 点赞对象接口
interface showLikeData {
    id: number
    isLiked: string
}
let getCommentLikeData = reactive<Record<number, showLikeData>>({})//以id为唯一键值，独立判断每个评论点赞状态
let isCommentLikeNum = ref<Record<number, string>>({})//以id为唯一键值，独立判断每个评论点赞状态
let getReplyLikeData = reactive<Record<number, showLikeData>>({})//以id为唯一键值，独立判断每个评论点赞状态
let isReplyLikeNum = ref<Record<number, string>>({})//以id为唯一键值，独立判断每个评论点赞状态
let JsonLike = reactive({})
// 获取每个评论点赞状态
async function getCommentLikeDataFrom(cid: number, index: number, content: string) {
    try {
        const CommentDataAxios = await axios({
            url: '/api/like/getLikeCommentRecord',
            params: { commentId: cid }
        })

        if (CommentDataAxios.data.data) {
            getCommentLikeData[cid] = CommentDataAxios.data.data
            isCommentLikeNum.value[cid] = getCommentLikeData[cid].isLiked || '0'
        } else {
            isCommentLikeNum.value[cid] = ''
        }

        localStorage.setItem(`comment_${cid}_like`, isCommentLikeNum.value[cid])
    } catch (error) {
        console.error('获取点赞状态失败:', error)
        const cachedLike = localStorage.getItem(`comment_${cid}_like`)
        isCommentLikeNum.value[cid] = cachedLike || '0'
    }
}

async function checkCommentLike(cid: number, index: number) {
    if (!isCommentLikeNum.value[cid] || isCommentLikeNum.value[cid] === '') {
        commentList[index].likeCount = commentList[index].likeCount + 1
        isCommentLikeNum.value[cid] = '1'
        localStorage.setItem(`comment_${cid}_like`, isCommentLikeNum.value[cid])

        JsonLike = {
            isLiked: isCommentLikeNum.value[cid],
            commentId: cid,
        }

        try {
            const response = await axios({
                url: '/api/like/thumbsUpComment',
                method: 'post',
                data: JSON.stringify(JsonLike),
                headers: { 'Content-Type': 'application/json' }
            })
            if (response.data.data) {
                getCommentLikeData[cid] = response.data.data
                isCommentLikeNum.value[cid] = response.data.data.isLiked
                localStorage.setItem(`comment_${cid}_like`, isCommentLikeNum.value[cid])
            }
        } catch (error) {
            console.log(error)
            isCommentLikeNum.value[cid] = '0'
            localStorage.setItem(`comment_${cid}_like`, '0')
        }
    }
    else if (isCommentLikeNum.value[cid] == '1') {
        commentList[index].likeCount = commentList[index].likeCount - 1

        isCommentLikeNum.value[cid] = '0'
        localStorage.setItem(`comment_${cid}_like`, isCommentLikeNum.value[cid])

        JsonLike = {
            id: getCommentLikeData[cid]?.id || -1,
            isLiked: isCommentLikeNum.value[cid],
            commentId: cid
        }

        try {
            const response = await axios({
                url: '/api/like/thumbsUpComment',
                method: 'post',
                data: JSON.stringify(JsonLike),
                headers: { 'Content-Type': 'application/json' }
            })
            if (response.data.data) {
                getCommentLikeData[cid] = response.data.data
                isCommentLikeNum.value[cid] = response.data.data.isLiked
                localStorage.setItem(`comment_${cid}_like`, isCommentLikeNum.value[cid])
            }
        } catch (error) {
            console.log(error)
            isCommentLikeNum.value[cid] = '1'
            localStorage.setItem(`comment_${cid}_like`, '1')
        }
    }
    else if (isCommentLikeNum.value[cid] == '0') {
        commentList[index].likeCount = commentList[index].likeCount + 1

        isCommentLikeNum.value[cid] = '1'
        localStorage.setItem(`comment_${cid}_like`, isCommentLikeNum.value[cid])

        JsonLike = {
            id: getCommentLikeData[cid]?.id || -1,
            isLiked: isCommentLikeNum.value[cid],
            commentId: cid
        }

        try {
            const response = await axios({
                url: '/api/like/thumbsUpComment',
                method: 'post',
                data: JSON.stringify(JsonLike),
                headers: { 'Content-Type': 'application/json' }
            })
            if (response.data.data) {
                getCommentLikeData[cid] = response.data.data
                isCommentLikeNum.value[cid] = response.data.data.isLiked
                localStorage.setItem(`comment_${cid}_like`, isCommentLikeNum.value[cid])
            }
            // 直接使用接口返回的最新数据更新状态
            if (response.data.data) {
                getCommentLikeData[cid] = response.data.data
                isCommentLikeNum.value[cid] = response.data.data.isLiked
                localStorage.setItem(`comment_${cid}_like`, isCommentLikeNum.value[cid])
            }
        } catch (error) {
            console.log(error)
            // 回滚状态
            isCommentLikeNum.value[cid] = '1'
            localStorage.setItem(`comment_${cid}_like`, '1')
        }
    }



    //取消后又点赞(由于之前取消点赞，此时置1)
    else if (isCommentLikeNum.value[cid] == '0') {
        commentList[index].likeCount = commentList[index].likeCount + 1

        console.log('进入0了');

        isCommentLikeNum.value[cid] = '1'
        // 更新localStorage
        localStorage.setItem(`comment_${cid}_like`, isCommentLikeNum.value[cid])

        JsonLike = {
            id: getCommentLikeData[cid]?.id || -1,
            isLiked: isCommentLikeNum.value[cid],
            commentId: cid
        }
        //发送点赞请求
        try {
            const response = await axios({
                url: '/api/like/thumbsUpComment',
                method: 'post',
                data: JSON.stringify(JsonLike),
                headers: { 'Content-Type': 'application/json' }
            })
            // 直接使用接口返回的最新数据更新状态
            if (response.data.data) {
                getCommentLikeData[cid] = response.data.data
                isCommentLikeNum.value[cid] = response.data.data.isLiked
                localStorage.setItem(`comment_${cid}_like`, isCommentLikeNum.value[cid])
            }
        } catch (error) {
            console.log(error)
            // 回滚状态
            isCommentLikeNum.value[cid] = '0'
            localStorage.setItem(`comment_${cid}_like`, '0')
        }

    }
    // getComment(true)
}

// 回复点赞的校验
async function checkReplyLike(cid: number, rid: number, index: number) {
    console.log('点击了回复点赞');

    // 第一次点赞，确保严格判断空字符串
    if (isReplyLikeNum.value[rid] === '') {
        console.log('回复进入空了');
        replyList[cid][index].likeCount = replyList[cid][index].likeCount + 1

        isReplyLikeNum.value[rid] = '1'
        localStorage.setItem(`reply_${rid}_like`, isReplyLikeNum.value[rid])

        JsonLike = {
            isLiked: isReplyLikeNum.value[rid],
            replyId: rid,
        }

        try {
            const response = await axios({
                url: '/api/like/thumbsUpReply',
                method: 'post',
                data: JSON.stringify(JsonLike),
                headers: { 'Content-Type': 'application/json' }
            })
            if (response.data.data) {
                getReplyLikeData[rid] = response.data.data

                isReplyLikeNum.value[rid] = response.data.data.isLiked
                localStorage.setItem(`reply_${rid}_like`, isReplyLikeNum.value[rid])
            }
        } catch (error) {
            console.log(error)
            isReplyLikeNum.value[rid] = '0'
            localStorage.setItem(`reply_${rid}_like`, '0')
        }
    }
    //取消点赞
    else if (isReplyLikeNum.value[rid] == '1') {
        console.log('回复进入1了');
        replyList[cid][index].likeCount = replyList[cid][index].likeCount - 1

        isReplyLikeNum.value[rid] = '0'
        localStorage.setItem(`reply_${rid}_like`, isReplyLikeNum.value[rid])

        JsonLike = {
            id: getReplyLikeData[rid].id,
            isLiked: isReplyLikeNum.value[rid],
            replyId: rid
        }

        try {
            const response = await axios({
                url: '/api/like/thumbsUpReply',
                method: 'post',
                data: JSON.stringify(JsonLike),
                headers: { 'Content-Type': 'application/json' }
            })
            if (response.data.data) {
                getReplyLikeData[rid] = response.data.data
                isReplyLikeNum.value[rid] = response.data.data.isLiked
                localStorage.setItem(`reply_${rid}_like`, isReplyLikeNum.value[rid])
            }
        } catch (error) {
            console.log(error)
            isReplyLikeNum.value[rid] = '1'
            localStorage.setItem(`reply_${rid}_like`, '1')
        }
    }
    //取消后又点赞
    else if (isReplyLikeNum.value[rid] == '0') {
        console.log('回复进入0了');
        replyList[cid][index].likeCount = replyList[cid][index].likeCount + 1

        isReplyLikeNum.value[rid] = '1'
        localStorage.setItem(`reply_${rid}_like`, isReplyLikeNum.value[rid])

        JsonLike = {
            id: getReplyLikeData[rid].id,
            isLiked: isReplyLikeNum.value[rid],
            replyId: rid
        }
        console.log(JsonLike);

        try {
            const response = await axios({
                url: '/api/like/thumbsUpReply',
                method: 'post',
                data: JSON.stringify(JsonLike),
                headers: { 'Content-Type': 'application/json' }
            })
            if (response.data.data) {
                getReplyLikeData[rid] = response.data.data
                isReplyLikeNum.value[rid] = response.data.data.isLiked
                localStorage.setItem(`reply_${rid}_like`, isReplyLikeNum.value[rid])
            }
        } catch (error) {
            console.log(error)
            isReplyLikeNum.value[rid] = '0'
            localStorage.setItem(`reply_${rid}_like`, '0')
        }
    }
}






</script>

<style scoped lang="scss">
.building {
    margin-top: 20px;
    padding: 0 16px;
}

.landLord {
    padding: 16px 0;
    border-bottom: 1px solid #f0f0f0;

    .el-image {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        vertical-align: middle;
        margin-right: 12px;
    }

    span {
        font-size: 14px;
        color: #333;
        font-weight: 500;
    }

    .landLordComment {
        margin: 12px 0 8px 52px;
        font-size: 18px;
        line-height: 1.5;
        color: #333;
    }

    .el-link {
        margin-left: 52px;
        font-size: 12px;
        color: #999;
        margin-right: 16px;

        &:hover {
            color: var(--el-color-primary);
        }
    }

    .el-form-item {
        margin-top: 12px;
        margin-left: 52px;
    }
}

.member {
    padding: 12px 0 12px 52px;
    border-top: 1px dashed #f0f0f0;

    .el-image {
        width: 32px;
        height: 32px;
        border-radius: 50%;
        vertical-align: middle;
        margin-right: 12px;
    }

    span {
        font-size: 13px;
        color: #666;
    }

    .landLordComment {
        margin: 8px 0 8px 44px;
        font-size: 13px;
        line-height: 1.5;
        color: #666;
    }

    .el-link {
        margin-left: 44px;
        font-size: 12px;
        color: #999;

        &:hover {
            color: var(--el-color-primary);
        }
    }

    .el-form-item {
        margin-top: 8px;
        margin-left: 44px;
    }
}

.el-link[show] {
    display: block;
    margin: 16px 0;
    text-align: center;
    color: var(--el-color-primary);
}

.el-form-item {
    margin-bottom: 16px;

    .el-button {
        margin-left: 12px;
    }
}

.smallIcon {
    display: inline-block;
}

.userHead {
    position: relative;
}

.commentNickName {
    position: absolute;
    top: 0;
    left: 50px;
}

.commentTime {
    position: absolute;
    bottom: 0;
    left: 50px;
}

.replyHead{
    position: relative;
}
.replyNickName{
    position: absolute;
    left: 45px;
    top: 0;
}
.replyTime{
    position: absolute;
    left: 45px;
    bottom: 0;
}
</style>
